﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebFrontEnd.Helpers;

namespace WebFrontEnd
{
    public partial class QRCodes : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int eid;
            if(!int.TryParse(Request.QueryString["eid"], out eid))
            {
                Response.Redirect("Default.aspx");
            }
            var ev = BL.GetEventById(eid);
            if (ev == null)
            {
                Response.Redirect("Default.aspx");
            }
            if (ev.UserID == GetCurrentUser().ID)
            {
                LoadInviteGifs(ev);
            }
            Response.Headers["content-disposition"] = "attachment; filename=" + ev.Name.Trim().Replace(' ', '_') + "_QRCodes.html";
        }

        private void LoadInviteGifs(BusinessLayer.BLServerReference.Event ev)
        {
            IQREncoder encoder = new MessagingToolkitQREncoder();
            var invites = BL.GetInvitesByEvent(ev);
            int num = 0;
            StringBuilder html = new StringBuilder("<table><tr>");
            string domainName = ConfigurationManager.AppSettings["DomainName"];
            foreach (var invite in invites)
            {
                if (num % 3 == 0)
                {
                    html.Append("</tr><tr>");
                }
                string rsvpLink = string.Format("http://{0}/RSVP.aspx?gid={1}&h={2}",ConfigurationManager.AppSettings.Get("DomainName"),invite.GuestID,invite.Hash);
                string imgFormat = @"<img width=""80"" height=""80"" src=""data:image/png;base64,{0}""/>";
                html.Append(string.Format("<td>{0}<div>{1}</div></td>",
                    invite.Guest.CombinedName(),
                    string.Format(imgFormat,
                    YorKinHTMLHelper.ImageToBase64(encoder.GetQRBitmap(rsvpLink),System.Drawing.Imaging.ImageFormat.Png))));
                num++;
            }
            html.Append("</tr></table>");
            mainTable.InnerHtml = html.ToString();
        }
    }
}